package com.qf.mybatisExam01.utils;

import com.qf.mybatisExam01.entity.Book;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class BookReader {
    private Integer batchNum = 2000; //默认读取数量
    private String filepath;  //文件路径
    private BufferedReader br;

    public BookReader(String filepath) throws FileNotFoundException {
        this.filepath = filepath;
        this.br = new BufferedReader(new FileReader(filepath));
    }

    public BookReader(Integer batchNum, String filepath) throws FileNotFoundException {
        this.batchNum = batchNum;
        this.filepath = filepath;
        this.br = new BufferedReader(new FileReader(filepath));
    }

    /**
     * 读取文件，然后返回List集合
     * @return
     * @throws IOException
     */
    public  List<Book> fileToListBooks() throws IOException {
        List<Book> books = new ArrayList<>();
        String content = null;
        while ( (content = br.readLine())!=null ){
            String[] split = content.split(",");
            String name = split[0];
            String author = split[1];
            String publish =  split[2];
            Integer sort = Integer.valueOf(split[3]);
            Book book = new Book(name,author,publish,sort);
            books.add(book);
            if (books.size()==batchNum){ // 读够一批的数量了
                return books;
            }
        }
        return books;
    }
    /**
     * 关闭相关的资源
     */
    public void close() throws IOException {

        this.br.close();

    }
}
